#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Provides an app to fill the environ with a user's roles
"""

from tack.db import query
from tack.lib import default401

auth_sql = """
SELECT auth_role.role_name
FROM auth_role
LEFT JOIN auth_login_role ON auth_role.role_id = auth_login_role.role_id
LEFT JOIN auth_login ON auth_login_role.login_id = auth_login.login_id
WHERE auth_login.login_name = %s
UNION
SELECT auth_role.role_name
FROM auth_role
LEFT JOIN auth_group_role on auth_role.role_id = auth_group_role.role_id
LEFT JOIN auth_login_group on auth_group_role.group_id = auth_login_group.group_id
LEFT JOIN auth_login on auth_login_group.login_id = auth_login.login_id
WHERE auth_login.login_name = %s"""


def authz(app, key='roles', handle401=default401):
    def authz_inner(environ, start_response):
        if 'REMOTE_USER' not in environ:
            return handle401(environ, start_response)
        user = environ['REMOTE_USER']
        result = query(environ['connection'], auth_sql, user, user)
        environ[key] = sorted([str(r[0]) for r in result])
        return app(environ, start_response)
    return authz_inner
